/**
 * 模型监控面板
 * 显示所有模型的健康状态和性能指标
 */

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Statistic, 
  Table, 
  Tag, 
  Progress, 
  Alert,
  Space,
  Tooltip,
  Button,
  Modal,
  Typography
} from 'antd';
import { 
  CheckCircleOutlined, 
  ExclamationCircleOutlined, 
  ClockCircleOutlined,
  DollarOutlined,
  ThunderboltOutlined,
  ReloadOutlined,
  SettingOutlined,
  LineChartOutlined
} from '@ant-design/icons';
import { ModelType, MODEL_CAPABILITIES } from '../../services/models/base-model-adapter';
import { ModelHealth } from '../../services/models/model-router';

const { Title, Text } = Typography;

export interface ModelDashboardProps {
  onRefresh?: () => void;
  onModelConfig?: (modelType: ModelType) => void;
}

export const ModelDashboard: React.FC<ModelDashboardProps> = ({
  onRefresh,
  onModelConfig
}) => {
  const [modelHealth, setModelHealth] = useState<ModelHealth[]>([]);
  const [loading, setLoading] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedModel, setSelectedModel] = useState<ModelType | null>(null);

  // 模拟获取模型健康数据
  useEffect(() => {
    fetchModelHealth();
  }, []);

  const fetchModelHealth = async () => {
    setLoading(true);
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const mockHealth: ModelHealth[] = [
      {
        modelType: ModelType.GPT4,
        isHealthy: true,
        lastCheck: new Date(),
        responseTime: 1200,
        errorRate: 0.02
      },
      {
        modelType: ModelType.GPT35,
        isHealthy: true,
        lastCheck: new Date(),
        responseTime: 800,
        errorRate: 0.01
      },
      {
        modelType: ModelType.CLAUDE,
        isHealthy: true,
        lastCheck: new Date(),
        responseTime: 1500,
        errorRate: 0.03
      },
      {
        modelType: ModelType.WENXIN,
        isHealthy: false,
        lastCheck: new Date(),
        responseTime: 0,
        errorRate: 0.25
      },
      {
        modelType: ModelType.QWEN,
        isHealthy: true,
        lastCheck: new Date(),
        responseTime: 900,
        errorRate: 0.05
      }
    ];
    
    setModelHealth(mockHealth);
    setLoading(false);
  };

  const handleRefresh = () => {
    fetchModelHealth();
    onRefresh?.();
  };

  const showModelDetail = (modelType: ModelType) => {
    setSelectedModel(modelType);
    setDetailModalVisible(true);
  };

  const getHealthyModelsCount = () => {
    return modelHealth.filter(h => h.isHealthy).length;
  };

  const getAverageResponseTime = () => {
    const healthyModels = modelHealth.filter(h => h.isHealthy);
    if (healthyModels.length === 0) return 0;
    
    return Math.round(
      healthyModels.reduce((sum, h) => sum + h.responseTime, 0) / healthyModels.length
    );
  };

  const getAverageErrorRate = () => {
    const healthyModels = modelHealth.filter(h => h.isHealthy);
    if (healthyModels.length === 0) return 0;
    
    return (
      healthyModels.reduce((sum, h) => sum + h.errorRate, 0) / healthyModels.length * 100
    ).toFixed(2);
  };

  const columns = [
    {
      title: '模型',
      dataIndex: 'modelType',
      key: 'modelType',
      render: (modelType: ModelType) => (
        <Space>
          <Text strong>{modelType}</Text>
          <Text type="secondary">
            {MODEL_CAPABILITIES[modelType]?.provider || 'Unknown'}
          </Text>
        </Space>
      )
    },
    {
      title: '状态',
      dataIndex: 'isHealthy',
      key: 'status',
      render: (isHealthy: boolean) => (
        <Tag 
          color={isHealthy ? 'success' : 'error'}
          icon={isHealthy ? <CheckCircleOutlined /> : <ExclamationCircleOutlined />}
        >
          {isHealthy ? '正常' : '异常'}
        </Tag>
      )
    },
    {
      title: '响应时间',
      dataIndex: 'responseTime',
      key: 'responseTime',
      render: (time: number, record: ModelHealth) => (
        <Space>
          <Text>{record.isHealthy ? `${time}ms` : 'N/A'}</Text>
          {record.isHealthy && (
            <Progress
              percent={Math.min((time / 3000) * 100, 100)}
              size="small"
              status={time > 2000 ? 'exception' : time > 1000 ? 'active' : 'success'}
              showInfo={false}
              style={{ width: 60 }}
            />
          )}
        </Space>
      )
    },
    {
      title: '错误率',
      dataIndex: 'errorRate',
      key: 'errorRate',
      render: (rate: number) => (
        <Space>
          <Text>{(rate * 100).toFixed(2)}%</Text>
          <Progress
            percent={rate * 100}
            size="small"
            status={rate > 0.1 ? 'exception' : rate > 0.05 ? 'active' : 'success'}
            showInfo={false}
            style={{ width: 60 }}
          />
        </Space>
      )
    },
    {
      title: '成本',
      dataIndex: 'modelType',
      key: 'cost',
      render: (modelType: ModelType) => (
        <Text>${MODEL_CAPABILITIES[modelType]?.costPer1kTokens || 'N/A'}/1K</Text>
      )
    },
    {
      title: '最后检查',
      dataIndex: 'lastCheck',
      key: 'lastCheck',
      render: (date: Date) => (
        <Text type="secondary">
          {date.toLocaleTimeString()}
        </Text>
      )
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: ModelHealth) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<LineChartOutlined />}
            onClick={() => showModelDetail(record.modelType)}
          >
            详情
          </Button>
          <Button
            type="text"
            size="small"
            icon={<SettingOutlined />}
            onClick={() => onModelConfig?.(record.modelType)}
          >
            配置
          </Button>
        </Space>
      )
    }
  ];

  const selectedModelHealth = selectedModel ? 
    modelHealth.find(h => h.modelType === selectedModel) : null;

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Space style={{ width: '100%', justifyContent: 'space-between' }}>
          <Title level={3}>模型监控面板</Title>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
          >
            刷新
          </Button>
        </Space>
      </div>

      {/* 总览统计 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总模型数"
              value={modelHealth.length}
              prefix={<ThunderboltOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="健康模型"
              value={getHealthyModelsCount()}
              suffix={`/ ${modelHealth.length}`}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ 
                color: getHealthyModelsCount() === modelHealth.length ? '#3f8600' : '#cf1322' 
              }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="平均响应时间"
              value={getAverageResponseTime()}
              suffix="ms"
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="平均错误率"
              value={getAverageErrorRate()}
              suffix="%"
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 健康状态警告 */}
      {modelHealth.some(h => !h.isHealthy) && (
        <Alert
          message="部分模型状态异常"
          description={`${modelHealth.filter(h => !h.isHealthy).length} 个模型当前不可用，请检查配置或联系管理员。`}
          type="warning"
          showIcon
          style={{ marginBottom: 24 }}
        />
      )}

      {/* 模型详细列表 */}
      <Card title="模型状态详情">
        <Table
          columns={columns}
          dataSource={modelHealth}
          rowKey="modelType"
          loading={loading}
          pagination={false}
          size="middle"
        />
      </Card>

      {/* 模型详情弹窗 */}
      <Modal
        title={`${selectedModel} 详细信息`}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedModelHealth && (
          <div>
            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="当前状态"
                    value={selectedModelHealth.isHealthy ? '正常' : '异常'}
                    valueStyle={{ 
                      color: selectedModelHealth.isHealthy ? '#3f8600' : '#cf1322' 
                    }}
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="响应时间"
                    value={selectedModelHealth.responseTime}
                    suffix="ms"
                  />
                </Card>
              </Col>
            </Row>

            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="错误率"
                    value={(selectedModelHealth.errorRate * 100).toFixed(2)}
                    suffix="%"
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="最后检查"
                    value={selectedModelHealth.lastCheck.toLocaleString()}
                  />
                </Card>
              </Col>
            </Row>

            {selectedModel && MODEL_CAPABILITIES[selectedModel] && (
              <Card title="模型能力" size="small">
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div>
                    <Text strong>提供商：</Text>
                    <Text>{MODEL_CAPABILITIES[selectedModel].provider}</Text>
                  </div>
                  <div>
                    <Text strong>最大Token：</Text>
                    <Text>{MODEL_CAPABILITIES[selectedModel].maxTokens}</Text>
                  </div>
                  <div>
                    <Text strong>支持语言：</Text>
                    <Space>
                      {MODEL_CAPABILITIES[selectedModel].languages.map(lang => (
                        <Tag key={lang}>{lang}</Tag>
                      ))}
                    </Space>
                  </div>
                  <div>
                    <Text strong>专长领域：</Text>
                    <Space>
                      {MODEL_CAPABILITIES[selectedModel].specialties.map(specialty => (
                        <Tag key={specialty} color="blue">{specialty}</Tag>
                      ))}
                    </Space>
                  </div>
                  <div>
                    <Text strong>成本：</Text>
                    <Text>${MODEL_CAPABILITIES[selectedModel].costPer1kTokens}/1K tokens</Text>
                  </div>
                </Space>
              </Card>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};
